package cn.itcast.bos.web.action.system;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Result;

import com.opensymphony.xwork2.ActionContext;

import cn.itcast.bos.domain.system.Menu;
import cn.itcast.bos.domain.system.User;
import cn.itcast.bos.service.system.UserSerivce;
import cn.itcast.bos.web.action.common.BaseAction;

public class UserAction extends BaseAction<User> {
	@Action(value = "user_login_ajax", results = { @Result(name = "success", type = "json") })
	// 基于shiro实现登录
	public String login() {
		// 创建储存数据的map结果集
		Map<String, Object> results = new HashMap<>();
		// 默认是通过的
		results.put("success", true);
		// 获取subject
		Subject subject = SecurityUtils.getSubject();
		AuthenticationToken token = new UsernamePasswordToken(model.getUsername(), model.getPassword());
		// 根据抛出的异常,处理业务逻辑
		try {
			subject.login(token);
		} catch (UnknownAccountException e) {
			// 用户名不存在
			e.printStackTrace();
			results.put("success", false);
			results.put("msg", "用户名不存在");
		} catch (IncorrectCredentialsException e) {
			// 用户名不存在
			e.printStackTrace();
			results.put("success", false);
			results.put("msg", "该用户名密码不正确");
		}
		//压栈
		ActionContext.getContext().getValueStack().push(results);
		
		return SUCCESS;
	}
	@Action(value = "user_logout", results = { @Result(name = "success", type = "redirect",location="login.html") })
	public String logout(){
		//基于shiro完成退出登录
		Subject subject = SecurityUtils.getSubject();
		subject.logout();
		return SUCCESS;
	}
	
	@Resource
	private UserSerivce service;
	
	@Action(value = "user_list", results = { @Result(name = "success", type = "json") })
	public String menu_list(){
		List<User> users = service.findAll();
		ActionContext.getContext().getValueStack().push(users);
		return SUCCESS;
	}
	//属性驱动,接收用户选择的角色
	private String[] roleIds;
	
	
	public void setRoleIds(String[] roleIds) {
		this.roleIds = roleIds;
	}
	@Action(value="user_save",results={@Result(name="success",type="redirect",location="pages/system/userlist.html")})
	public String user_save(){
		service.saveUser(model,roleIds);
		return SUCCESS;
	}
}
